#!/usr/bin/python
#coding=utf-8

# Steven Lian modified on 2016/7/21
# Purpose: for irda data service test
# 这个软件运行在红外校验服务器的请求,负责处理来自PC的post请求 并发送到相应的redis数据库.
# redis数据库在红外校验服务器

import json, platform
import redis
import sys
import logging

_DEBUG=False
#是否将日志写到db中 
_TOLOG = True  

if _DEBUG ==True:
    import pdb
    pdb.set_trace()

# Redis/mongodb server information  BEGIN  
_REDIS_PORT=6379
_REDIS_DB=2


if platform.system() == 'Linux' :
    _REDIS_SERVERADDR = "127.0.0.1" 
    _WINDOWS_FLAG=False
else:
    _WINDOWS_FLAG=True
    sys.path.append("..\\..")
    #_REDIS_SERVERADDR = "118.192.76.159"
    _REDIS_SERVERADDR = "120.132.55.236"
    #client = pymongo.MongoClient("118.192.76.159", 28088)

#redis server
if _WINDOWS_FLAG<>True:
    controlServer = redis.ConnectionPool(host=_REDIS_SERVERADDR, port=_REDIS_PORT, db=_REDIS_DB)
    rControl = redis.Redis(connection_pool=controlServer)

#log BEGIN
# 0-->ALL, 1 -->ERROR 
_LOG_LEVEL=0 
if _WINDOWS_FLAG == False :
    uwsgilogfile="../../log/uwsgilog"
else :
    uwsgilogfile="uwsgilog"

# the function to set log file, SL:2014/10/3
def setlog(title,logfile) : 
    logger = logging.getLogger(title)   
    formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(message)s')    
    file_handler = logging.FileHandler(logfile) 
    #file_handler = TimedRotatingFileHandler(logfile,when="D")
    file_handler.setFormatter(formatter)        
    #stream_handler = logging.StreamHandler(sys.stderr) 
    logger.addHandler(file_handler) 
    #logger.addHandler(stream_handler)  
    logger.setLevel(logging.INFO)   
    return logger

uwsgilog = setlog("TEST",uwsgilogfile)
#log END


#count for typeID
gTokenPrefix="TESTID."

def getTokenVal(token, val=0):
    global gTokenPrefix, rControl
    result=0
    if _WINDOWS_FLAG<>True:
        realToken=gTokenPrefix+token
        nExist=rControl.exists(realToken)
        if nExist>0:
            if val==0:
                nCount=rControl.get(realToken)
            else:
                nCount=rControl.incr(realToken, val)
            nCount=int(nCount)
        else:
            nCount=-1
        result =nCount
    return result


# setTokenVal: 
# request: token and value, 
# return: current token count
def setTokenVal(token, val):
    global gTokenPrefix, rControl
    result=0
    if _WINDOWS_FLAG<>True:
        realToken=gTokenPrefix+token
        rControl.set(realToken, val)
        nCount=rControl.get(realToken)
        nCount=int(nCount)
        result =nCount
    return result

def embededLog(param):
    return param


# del a Token: 
# request: token 
# return: 
def delAToken(token):
    global gTokenPrefix, rControl
    result=0
    if _WINDOWS_FLAG<>True:
        realToken=gTokenPrefix+token
        nCount=rControl.delete(realToken)
        nCount=int(nCount)
    return result
    
def jsonDumps(data):
	return json.dumps(data,separators=(',', ':'))	 

def post(postdata,IP):
    if _LOG_LEVEL ==0:
        uwsgilog.info('R:'+ postdata )
    else:
        uwsgilog.error('R:'+ postdata)
    result={"CMD":"ERR", "data":""}
    data = ""
    
    try:
        d = json.loads(postdata)
        d["IP"] = IP
        CMD=""
        if "token" in d:
            token=d["token"]
        else:
            CMD="ERR"
            data="no token"
        if "CMD" in d and CMD=="":
            CMD=d["CMD"]
            if CMD=="set":
                val=d["value"]
                data=setTokenVal(token, val)
            elif CMD=="get":
                data=getTokenVal(token, 0)
            elif CMD=="del":
                data=delAToken(token)
            elif CMD=="log":
                if "param" in d:
                    data=embededLog(d["param"])
            else:
                CMD="ERR"
                data="no CMD"
        result["CMD"]=CMD
        result["data"]=data
    except:
        pass
    data=jsonDumps(result)
    
    if _LOG_LEVEL ==0:
        uwsgilog.info( 'S:'+data )
    else:
        uwsgilog.error('S:'+data)
    return data



if platform.system() <> 'Linux' or _DEBUG==True:
    IP='127.0.0.1'


    msg='{"token":"100000","CMD":"get"}'
    msg='{"token":"100000","CMD":"set","value":100}'
    #msg='{"token":"100000","CMD":"del"}'
    #msg='{"token":"100000","CMD":"el"}'
    #msg='{"KK":"100000","CMD":"del"}'
    msg='{"token":"100000","CMD":"log","param":"test sss"}'
    
    t=post(msg,IP)

    print t
